<?php

namespace Biz\service\wiki;

use Biz\model\brand\CustomCategoryWiki as mCustomCategoryWiki;
use Biz\model\brandActivity\BrandActivityBasic;
use Biz\model\store\StoreBasic;
use Biz\model\store\StoreCustomCategoryWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\model\wiki\WikiBasicLog as mWikiBasicLog;
use Biz\module\Classes\wiki\Wiki as clsWiki;
use Biz\module\Classes\wiki\WikiBasic as clsWikiBasic;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\brand\Brand;
use Biz\service\brand\BrandActivity;
use Biz\service\Store\StoreBasicService;
use Biz\tools\RealUrl;
use Doraemon\cache\UserCounter;
use Doraemon\model\Category as mCategory;
use Doraemon\model\NewTag\Tag;
use Doraemon\service\Category;
use Doraemon\tools\ImgUpload;
use Doraemon\tools\Log;
use Doraemon\tools\SensitiveWord;
use Exception;


class WikiBasic
{
    //wiki
    private const BRAND_TAG_SPACE = 399;//空间
    private const BRAND_TAG_STYLE = 119;//风格
    private const BRAND_TAG_MATERIAL = 139;//材质
    public const WIKI_BASIC_IMAGE_STATUS_WAIT = 2; //图片状态：0：默认  1：已审核-通过  2：未审核  3：审核未通过
    public const WIKI_BASIC_IMAGE_STATUS_DONE = 1; //图片状态：0：默认  1：已审核-通过  2：未审核  3：审核未通过
    public const WIKI_BASIC_IMAGE_STATUS_DEFAULT = 0; //图片状态：0：默认  1：已审核-通过  2：未审核  3：审核未通过
    public const WIKI_BASIC_IMAGE_STATUS_UNPASS = 3; //图片状态：0：默认  1：已审核-通过  2：未审核  3：审核未通过
    //'审核状态 0：默认  1：已审核  2：未审核'
    public const IMGS_STATUS_DEFAULT = 0;
    public const IMGS_STATUS_DONE = 1;
    public const IMGS_STATUS_WAIT = 2;

    public const IMGS_STATUS = [
        self::IMGS_STATUS_WAIT => '待审核',
        self::IMGS_STATUS_DONE => "已审核",
    ];


    use _Async;

    /**
     * @param int $brandId
     * @param array $where
     * @param int $storeId
     * @return array
     */
    public static function bGetBrandWikiList(int $brandId = 0, array $where, int $storeId = 0): array
    {
        $list = [];
        $total = 0;
        //过滤掉没有官方商品的wiki
        if ($brandId > 0) {
            $ids = mWiki::selectByWhere(['brand_id' => $brandId, 'is_official' => 1], 'basic_id');
            $ids = array_unique($ids);
        }
        if ($storeId > 0) {
            $ids = mWiki::selectByWhere(['store_id' => $storeId, 'is_official' => 1], 'basic_id');
            $ids = array_unique($ids);
        }
        if ($ids) {
            if (!isset($where['id']) || !$where['id']) {
                $where['id'] = $ids;
            }
            if ($brandId > 0) {
                $where['brand_id'] = $brandId;
            }

            if ($storeId > 0) {
                $where['store_id'] = $storeId;
            }

            if ($where['basic_state'] == mWikiBasic::STATE_EDIT_AUDIT) {
                unset($where['basic_state']);
                $logWhere['operate_type'] = mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT;
                $logWhere['operate_value'] = mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE;
                $logWhere['log_state'] = mWikiBasicLog::STATE_NORMAL;
                $logWhere['basic_id'] = $ids;
                $editAuditBasicIds = mWikiBasicLog::selectByWhere($logWhere, 'basic_id');
                if ($editAuditBasicIds) {
                    $where['id'] = $editAuditBasicIds;
                } else {
                    return ['list' => [], 'total' => 0];
                }
            }
            $wikiBasicList = mWikiBasic::selectByWhere($where);
            $basicIds = array_column($wikiBasicList, 'id');
            if ($basicIds) {
                $basicLogList = mWikiBasicLog::selectByWhere([
                    'basic_id' => $basicIds,
                    'log_state[!]' => mWikiBasicLog::STATE_DEL,
                    'ORDER' => ['id' => 'DESC'],
                ]);

                $activityList = $basicIds ? BrandActivity::bGetWikiBasicActivity($basicIds) : [];

                $editAuditDataBasicId = [];
                $unPassDataReason = [];
                foreach ($basicLogList as $row) {
                    if ($row['operate_type'] == mWikiBasicLog::OPERATE_TYPE_AUDIT && $row['operate_value'] == mWikiBasic::STATE_NOT_PASS && !isset($unPassDataReason[$row['basic_id']])) {
                        $operateData = $row['operate_data'];
                        $operateData = $operateData ? json_decode($operateData, true) : [];
                        $reason = $operateData ? $operateData['reason'] : '';
                        $unPassDataReason[$row['basic_id']] = $reason;
                    }
                    if ($row['operate_type'] == mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT && $row['operate_value'] == mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE && !isset($editAuditDataBasicId[$row['basic_id']])) {
                        if ($row['log_state'] == mWikiBasicLog::STATE_NORMAL) {
                            $editAuditDataBasicId[$row['basic_id']] = $row['basic_id'];
                        }
                    }
                }
                unset($where['LIMIT']);
                unset($where['ORDER']);
                $total = mWikiBasic::selectCountWhere($where);


                $wikiListWhere['basic_id'] = $basicIds;
                $wikiListWhere['status[!]'] = mWiki::STATUS_DEL;
                $wikiListWhere['is_official'] = mWiki::IS_OFFICIAL_Y;
                if ($brandId > 0) {
                    $wikiListWhere['brand_id'] = $brandId;
                }
                if ($storeId > 0) {
                    $wikiListWhere['store_id'] = $storeId;
                }

                $wikiList = mWiki::selectByWhere($wikiListWhere);
                $wikiSpuList = [];
                $categoryIds = [];
                foreach ($wikiList as $row) {
                    $wikiSpuList[$row['basic_id']][] = $row;
                    $categoryIds[] = $row['category_id'];
                    $categoryIds[] = $row['second_category_id'];
                    $categoryIds[] = $row['third_category_id'];
                    $categoryIds[] = $row['four_category_id'];
                }
                $categoryIds = array_filter($categoryIds);
                $categoryList = $categoryIds ? mCategory::getCategoryList($categoryIds) : [];
                $categoryList = $categoryList ? array_column($categoryList, null, 'id') : [];
                foreach ($wikiBasicList as $row) {
                    $categoryName = '';
                    if ($row['category_id'] && isset($categoryList[$row['category_id']])) {
                        $categoryName .= $categoryList[$row['category_id']]['cate_name'];
                    }
                    if ($row['second_category_id'] && isset($categoryList[$row['second_category_id']])) {
                        $categoryName .= '>' . $categoryList[$row['second_category_id']]['cate_name'];
                    }
                    if ($row['third_category_id'] && isset($categoryList[$row['third_category_id']])) {
                        $categoryName .= '>' . $categoryList[$row['third_category_id']]['cate_name'];
                    }
                    if ($row['four_category_id'] && isset($categoryList[$row['four_category_id']])) {
                        $categoryName .= '>' . $categoryList[$row['four_category_id']]['cate_name'];
                    }
                    $reason = ($row['basic_state'] != mWikiBasic::STATE_NOT_PASS) ? '' : (isset($unPassDataReason[$row['id']]) ? $unPassDataReason[$row['id']] : '');
                    $status = isset($editAuditDataBasicId[$row['id']]) ? (string)mWikiBasic::STATE_EDIT_AUDIT : $row['basic_state'];
                    $cover_img = $info['cover_img_url'] ?? '';
                    $wikiInfo = [
                        'wiki_id' => $row['id'],
                        'title' => $row['title'],
                        'spu_title' => '',
                        'cover_img' => $cover_img,
                        'category_name' => $categoryName,
                        'spu_list' => [],
                        'series' => $row['series'],
                        'addtime' => date('Y.m.d', strtotime($row['addtime'])),
                        'status' => $status,
                        'reason' => $reason,
                        'basic_id' => $row['id'],
                    ];
                    $spuTitle = '';
                    if (isset($wikiSpuList[$row['id']])) {
                        foreach ($wikiSpuList[$row['id']] as $spuInfo) {
                            if (empty($wikiInfo['cover_img']) && $spuInfo['is_default']) {
                                $wikiInfo['cover_img'] = $spuInfo['cover_img'];
                            }
                            $wikiInfo['spu_list'][] = [
                                'id' => $spuInfo['id'],
                                'channel' => mWiki::CHANNEL_MAP[$spuInfo['channel']],
                                'spu_title' => $spuInfo['title'],
                                'channel_spu_id' => $spuInfo['channel_spu_id'],
                                'is_default' => $spuInfo['is_default'],
                            ];
                            //显示商品价格区间
                            if ($spuInfo['is_default'] == mWiki::IS_DEFAULT) {
                                $wikiInfo['min_price'] = $spuInfo['min_price'];
                                $wikiInfo['max_price'] = $spuInfo['max_price'];
                                $wikiInfo['price'] = $spuInfo['min_price'];
                            }
                            if ($spuInfo['is_default']) {
                                $spuTitle = $spuInfo['title'];
                            }
                            if (isset($activityList[$row['id']])) {
                                $wikiInfo['activity_list'] = [];
                                foreach ($activityList[$row['id']] as $activityInfo) {
                                    $wikiInfo['activity_list'][] = [
                                        'activity_type' => $activityInfo['activity_type'],
                                        'start_time' => $activityInfo['start_time'],
                                        'end_time' => $activityInfo['end_time'],
                                    ];
                                }
                            }
                        }
                    }
                    $wikiInfo['spu_title'] = $spuTitle;
                    $list[] = $wikiInfo;
                }
            }
        }

        return ['list' => $list, 'total' => $total];
    }

    public static function bGetBrandWiki($id)
    {
        if ($id) {
            $info = mWikiBasic::getByWhere(['id' => $id]);
            $wikiSpuList = mWiki::selectByWhere([
                'basic_id' => $id,
                'status[!]' => mWiki::STATUS_DEL,
                'is_official' => 1,
            ]);
            foreach ($wikiSpuList as $row) {
                $info['spu_list'][] = [
                    'id' => $row['id'],
                    'channel_spu_id' => $row['channel_spu_id'],
                    'channel_jump_params' => $row['channel_jump_params'],
                    'channel' => $row['channel'],
                    'is_default' => $row['is_default'],
                ];
                if ($row['is_default'] == mWiki::IS_DEFAULT) {
                    $info['min_price'] = $row['min_price'];
                    $info['max_price'] = $row['max_price'];
                    $info['price'] = $row['min_price'];
                }
            }
            $ids = [
                $info['category_id'],
                $info['second_category_id'],
                $info['third_category_id'],
                $info['four_category_id'],
                $info['last_category_id'],
            ];
            $ids = array_filter($ids);
            $list = Category::getCategoryList($ids);
            foreach ($list as $row) {
                if ($row['deep'] == 1) {
                    $info['first_cate_name'] = $row['cate_name'];
                    $info['category_name'] .= $row['cate_name'];
                } else {
                    if ($row['deep'] == 2) {
                        $info['second_cate_name'] = $row['cate_name'];
                        $info['category_name'] .= '/' . $row['cate_name'];
                    } else {
                        if ($row['deep'] == 3) {
                            $info['third_cate_name'] = $row['cate_name'];
                            $info['category_name'] .= '/' . $row['cate_name'];
                        } else {
                            if ($row['deep'] == 4) {
                                $info['four_cate_name'] = $row['cate_name'];
                                $info['category_name'] .= '/' . $row['cate_name'];
                            }
                        }
                    }
                }
            }
        }
        $tags = Tag::getAttrTagsWiki();
        $info['space_list'] = [];
        $info['style_list'] = [];
        $info['material_list'] = [];
        foreach ($tags as $row) {
            if ($row['parent_id'] == self::BRAND_TAG_SPACE) {//空间
                $info['space_list'][] = $row['tag'];
            } else {
                if ($row['parent_id'] == self::BRAND_TAG_STYLE) {//风格
                    $info['style_list'][] = $row['tag'];
                } else {
                    if ($row['parent_id'] == self::BRAND_TAG_MATERIAL) {//材质
                        $info['material_list'][] = $row['tag'];
                    }
                }
            }
        }
        $info['channel_list'] = [mWiki::CHANNEL_TAOBAO => '淘宝', mWiki::CHANNEL_JD => '京东'];

        return $info;
    }

    /**
     * 判断并上传url图片
     * @param array $data
     * @param int $brand_id
     * @return array[]
     */
    public static function _isImgId(array $data, $basic_id = 0): array
    {
        if ($data) {
            foreach ($data as $k => $v) {
                if (filter_var($v['img'], FILTER_VALIDATE_URL) !== false) {
                    $path = sys_get_temp_dir() . '/basic_' . $basic_id . '_' . $k . '.jpg';
                    $data[$k]['img'] = ImgUpload::uploadImgsByUrl($v['img'], $path);
                }
            }
        }

        return $data;
    }

    /**
     * 批量添加品牌wiki
     * @param $brandId
     * @param $brandType
     * @param $data
     * @return array
     * @throws \Exception
     */
    public static function bBatchAddBrandWiki($brandId, $brandType, $data)
    {
        $msg = [];
        $wikiData = [];
        $dataChannelSpu = [];
        $i = 1;
        $success = 0;
        $error = 0;
        $errorArr = [];
        $count = count($data);
        $where = [];
        foreach ($data as $row) {
            $row['title'] = trim($row['title']);
            if (!empty($row['title']) && !empty($row['channel']) && !empty($row['channel_spu_id'])) {
                if (!self::filterKey($row['title'])) {
                    throw new Exception('您提交的信息中包含敏感词或直接使用了分类名称，请做调整后再提交');
                }
                if (strpos($row['title'], '举例') === false) {//不包含举例
                    if (strpos($row['channel'], '京东') !== false) {
                        $channel = mWiki::CHANNEL_JD;
                        $dataRow = [
                            'channel' => $channel,
                            'channel_spu_id' => $row['channel_spu_id'],
                        ];
                        $wikiData[$row['title']][] = $dataRow;
                        $dataChannelSpu[$channel . '_' . $row['channel_spu_id']] = $row;
                        $where['OR']['AND #' . $i] = $dataRow;
                        $i++;
                    } else {
                        if (strpos($row['channel'], '淘宝') !== false || strpos($row['channel'], '天猫') !== false) {
                            $channel = mWiki::CHANNEL_TAOBAO;
                            $dataRow = [
                                'channel' => $channel,
                                'channel_spu_id' => $row['channel_spu_id'],
                            ];
                            $wikiData[$row['title']][] = $dataRow;
                            $dataChannelSpu[$channel . '_' . $row['channel_spu_id']] = $row;
                            $where['OR']['AND #' . $i] = $dataRow;
                            $i++;
                        }
                    }
                }
            }
        }
        if (!$where) {
            throw  new Exception('excel 数据错误');
        }
//        //认证品牌仅可添加 8 个商品
//        if (!in_array($brandType, [mBrand::BRAND_TYPE_BEST, mBrand::BRAND_TYPE_SUPER])) {
//            $data['series'] = '';//所属系列：仅精选品牌可用，对认证品牌置灰展示该项
//            $basicIds = mWiki::selectByWhere(['brand_id' => $brandId, 'status[!]' => mWiki::STATUS_DEL, 'is_official' => 1], 'basic_id');
//            $wikiCount = mWikiBasic::selectCountWhere(['brand_id' => $brandId, 'basic_state[!]' => mWikiBasic::STATE_DEL, 'id' => $basicIds]);
//            $wikiCount = $wikiCount + count($wikiData);
//            if ($wikiCount >= 8) {
//                throw new \Exception('入驻品牌专区即可无限添加商品');
//            }
//        }
        $wikiSpuList = mWiki::selectByWhere($where);
        $wikiChannelSpu = [];
        $otherBrandSpu = false;
        $checkBasicIdsArr = [];
        foreach ($wikiSpuList as $row) {
            $wikiChannelSpu[$row['channel'] . '_' . $row['channel_spu_id']] = $row;
            if ($row['brand_id'] && $row['brand_id'] != $brandId) {
                $msg['msg'] = [
                    '0个商品提交成功',
                    $count . '个商品提交失败',
                ];
                $msg['error'][] = '表格中商品 ID 为 ' . $row['channel_spu_id'] . ' 的商品校验不通过，建议删除后重新上传表格';
                $otherBrandSpu = true;
            }
            $checkBasicIdsArr[$row['basic_id']] = $row['channel_spu_id'];
        }
        if ($checkBasicIdsArr) {
            $errorMsgs = WikiBasic::bCheckBasic($checkBasicIdsArr, true);
            foreach ($errorMsgs as $errMsg) {
                $msg['msg'] = [
                    '0个商品提交成功',
                    $count . '个商品提交失败',
                ];
                $msg['error'][] = $errMsg;
                $otherBrandSpu = true;
            }
        }
        if ($otherBrandSpu) {
            return $msg;
        }
        $basicIds = [];
        foreach ($wikiData as $title => $spuList) {
            $wikiBasicData = [
                'brand_id' => $brandId,
                'title' => $title,
                'basic_state' => mWikiBasic::STATE_NORMAL,
            ];
            $basicId = mWikiBasic::insertData($wikiBasicData);
            if ($basicId) {
                $basicIds[] = $basicId;
                foreach ($spuList as $spu) {
                    $wikiSpuData = [
                        'basic_id' => $basicId,
                        'channel' => $spu['channel'],
                        'channel_type' => clsWiki::getChannelType($spu['channel']),
                        'channel_spu_id' => $spu['channel_spu_id'],
                        'brand_id' => $brandId,
                        'is_official' => 1,
                    ];
                    if (isset($wikiChannelSpu[$spu['channel'] . '_' . $spu['channel_spu_id']])) {
                        if ($wikiChannelSpu[$spu['channel'] . '_' . $spu['channel_spu_id']]['status'] == mWiki::STATUS_DEL) {
                            $wikiSpuData['status'] = mWiki::STATUS_NORMAL;
                        }
                        $result = mWiki::updateData($wikiSpuData,
                            ['channel' => $spu['channel'], 'channel_spu_id' => $spu['channel_spu_id']]);
                        if ($result) {
                            $success++;
                        } else {
                            Log::wiki_batchAdd_warning('商品「' . $title . '」添加失败。商品id：' . $spu['channel_spu_id'] . '#result:' . $result . '#sql:' . json_encode(mWiki::log()));
                            $errorArr[] = '商品「' . $title . '」添加失败。商品id:' . $spu['channel_spu_id'];
                            $error++;
                        }
                    } else {
                        $wikiSpuData['source_basic_id'] = $basicId;
                        $wikiId = mWiki::insertData($wikiSpuData);
                        if ($wikiId) {
                            $itemId = $wikiSpuData['channel_spu_id'];
                            $type = $wikiSpuData['channel_type'];
                            $channelJumpParams = isset($wikiSpuData['channel_jump_params']) ? $wikiSpuData['channel_jump_params'] : '';
                            $channelShopId = isset($wikiSpuData['channel_shop_id']) ? $wikiSpuData['channel_shop_id'] : 0;
                            $url = RealUrl::formatLink($itemId, $type, $channelJumpParams, $channelShopId);
                            if ($url) {
                                //添加抓取wiki任务
                                Wiki::addGetWikiSpuTask($url);
                            }
                            $success++;
                        } else {
                            Log::wiki_batchAdd_warning('商品「' . $title . '」添加失败。商品id：' . $spu['channel_spu_id'] . '#wiki_id:' . $wikiId . '#sql:' . json_encode(mWiki::log()));
                            $errorArr[] = '商品「' . $title . '」添加失败。商品id:' . $spu['channel_spu_id'];
                            $error++;
                        }
                    }
                }
            }
        }
        $msg['msg'] = [
            $success . '个商品提交成功',
            $error . '个商品提交失败',
        ];
        $msg['error'] = $errorArr;
        self::afterChangeBasic($basicIds, $brandId);

        return $msg;
    }

    public static function filterKey($key)
    {
        $cateArr = [
            "家具", "家居装饰", "家居日用", "家电", "灯饰建材", "床", "沙发", "椅", "凳", "桌", "几", "柜", "架", "布艺装饰", "装饰品", "床上用品", "餐厨用品", "收纳工具", "日用小件", "清洁用品", "厨卫电器", "生活电器", "灯具灯饰", "墙纸地面", "五金电工", "装修定制", "家具配件", "玩具", "屏风", "双层儿童床", "婴儿床", "单层儿童床", "懒人沙发", "高脚凳", "坐墩", "条凳", "餐桌", "书桌", "梳妆台", "茶几", "边几", "衣柜", "鞋柜", "电视柜", "餐边柜", "斗柜", "书柜", "床头柜", "衣帽架", "鞋架", "书架", "置物架", "帘子", "抱枕坐垫", "地毯地垫", "窗帘配件", "装饰字画", "钟表", "镜子", "香薰蜡烛", "花艺", "墙饰", "桌面装饰", "床垫", "床幔", "蚊帐", "被褥", "毯子", "枕头", "床品", "凉席", "餐具", "咖啡/茶具", "厨房工具", "餐厨布艺", "烘焙用品", "厨房收纳", "卫浴收纳", "杂物整理", "文具", "日用杂货", "台灯", "吊灯", "落地灯", "射灯筒灯", "吸顶灯", "壁灯", "灯具配件", "数码影音", "清洁电器", "美容美体", "个护", "日用电器", "厨卫大电", "厨卫小电", "数码配件", "影音产品", "智能家居", "安防", "生活", "清洁护理剂", "清洁工具", "宠物用品", "物品", "食品", "单人床", "双人床", "单人沙发", "双人沙发", "灯罩", "灯泡", "灯轨", "灯座", "灯串", "夜灯", "碗", "餐盘", "刀叉勺", "筷", "锅", "铲勺", "厨刀\菜刀", "剪", "砧板\菜板\面包板", "桌布", "桌旗", "围裙", "餐巾\茶巾", "餐垫", "厨房秤", "计时器", "烤盘\模具", "茶艺配件", "衣物清洁护理剂", "扫帚", "拖把", "百洁布\洗碗布\抹布", "刷子", "油烟机", "集成灶", "冰箱", "热水器", "洗碗机", "消毒柜", "嵌入式蒸烤箱", "冰柜", "壁挂炉", "烤箱", "电烤炉", "蒸箱", "净水器", "酒柜", "微波炉", "切菜机", "电饭煲", "水壶", "面包机", "养生壶", "饮水机", "打蛋器", "搅拌机", "榨汁机", "空气炸锅", "电磁炉", "冰淇淋机", "豆浆机", "酸奶机", "原汁机", "咖啡机", "料理机", "吸尘器", "扫地机器人", "新风机", "空气净化机", "空气检测仪", "除螨仪", "毛球清理器", "蒸汽拖把", "擦窗机器人", "洗衣机", "淋浴器", "排风扇", "浴霸", "马桶盖", "厨宝", "烘干机", "空调", "暖风机", "电扇", "除湿机", "加湿器", "电熨斗", "挂烫机", "电热毯", "吊扇", "路由器", "插线板", "充电器", "音频线", "摄像头", "音响", "耳机", "投影仪", "家庭影院", "电视机", "游戏机", "电吹风", "直发器", "卷发棒", "电动推子", "剃须刀", "电动牙刷", "洗脸仪", "美容仪", "剃毛器", "按摩仪", "调料瓶\油壶\研磨瓶", "保鲜盒\密封罐", "厨房收纳架\挂杆挂钩", "沥水篮\垫", "牙刷架", "吹风机架", "肥皂托\盒", "分液瓶", "收纳箱", "收纳盒", "收纳筐", "收纳篮", "收纳袋", "挂钩挂架", "收纳板\洞洞板及配件", "抱枕/靠垫", "坐垫", "窗帘", "浴帘", "门帘", "地毯", "装饰画", "画框/相框", "挂钟", "壁挂镜", "穿衣镜", "台面镜/化妆镜", "无火香薰\精油", "香薰蜡烛", "烛台\香台", "挂毯\挂布\挂旗", "挂盘", "墙面装饰品", "厨卫清洁护理剂", "垃圾桶", "除尘粘毛棒\鸡毛掸", "摆件", "音乐盒", "存钱罐", "烟灰缸", "咖啡研磨机", "厨师机", "其他清洁电器", "三人沙发", "厨卫配件", "花瓶", "仿真花", "花盆", "干花", "鲜花", "绿植", "座钟/台钟/闹钟", "矮凳", "奶泡机", "电蒸笼/电蒸锅", "帘子杆", "沙发罩", "卫浴", "厨房", "花洒", "垃圾处理器", "花洒头", "整体花洒", "恒温花洒", "马桶", "普通马桶", "壁挂马桶", "龙头", "面盆", "台上面盆", "台下面盆", "其他五金件", "地漏", "洗衣机地漏", "洗衣机龙头", "角阀", "厨房龙头", "虚拟商品", "服务费用", "吉博力服务费", "地垫", "油漆（废）", "瓷砖", "地板", "壁纸", "商品补拍", "转角沙发", "餐椅", "扶手椅", "吧台椅", "摇椅", "转椅", "躺椅", "儿童椅", "梳妆凳", "儿童凳", "换鞋凳", "餐凳", "儿童桌", "小推车", "墙面置物架", "落地置物架", "单层成人床", "装饰蜡烛", "车载香薰", "扩香片\扩香器", "线香\盘香\锥香", "仿真绿植", "园艺配件", "香薰配件\火柴\灭烛器", "冰箱贴", "布艺家纺", "毛巾浴巾", "毛巾", "浴巾", "家居服饰", "家居服\睡衣\浴袍", "家居鞋", "眼罩", "袜子", "内衣", "水具", "杯垫", "玻璃杯", "陶瓷杯\骨瓷杯", "搪瓷杯", "金属杯", "保温杯\旅行杯", "保温壶", "凉水壶", "烧水壶", "酒具", "酒杯\酒盅", "高脚杯", "酒瓶", "开瓶器", "酒瓶塞", "醒酒器\温酒器", "茶杯\咖啡杯", "茶壶\咖啡壶", "茶具套装", "茶盘", "咖啡配件", "量杯\量勺", "刮刀", "烘焙垫\硅胶垫\揉面垫", "擀面杖", "油刷\硅胶刷", "打蛋器\分蛋器", "料理盆\滤水盆\洗菜盆", "隔热垫\锅垫", "冰淇凌机\碎冰机\冰格\制冰袋", "隔热手套", "厨房实用小工具", "筷子笼", "刀架", "厨房纸巾架", "米箱", "抽屉分隔器", "浴室置物架", "毛巾\浴巾架", "纸巾架", "服装收纳", "衣架\裤架", "晾衣架", "脏衣篮", "衣物收纳盒", "桌面收纳", "纸巾盒", "托盘", "文具收纳", "首饰收纳", "化妆品收纳", "收纳罐", "桌面收纳篮\盒", "桌面收纳架", "工具箱", "医药箱", "雨伞架", "书立", "笔", "本\册\纸张", "日历", "文具杂货", "个人护理", "护理工具", "个人洗护", "箱包", "行李箱", "购物袋", "双肩包", "斜挎包", "墙面地面清洁护理剂", "除味除湿剂", "餐具套装", "饭盒\饭盒配件\焖烧杯", "清洁品收纳", "浴室柜", "墙地辅材", "油漆（新）", "浴缸", "吊椅", "工艺品", "杂志架", "DIY材料", "门", "窗", "吊顶", "水槽", "隔断", "玄关桌", "盆\桶", "暗盒", "燃气灶"
        ];
        if (in_array($key, $cateArr)) {
            return false;
        } else {
            if (SensitiveWord::check($key)) {//有违禁词
                return false;
            }
        }
        return true;
    }

    /**
     * 检查basic 是否在参加活动或则已上榜单
     * @param $checkBasicIdsArr
     * @param bool $returnMsg
     * @return array
     * @throws \Exception
     */
    public static function bCheckBasic($checkBasicIdsArr, $returnMsg = false)
    {
        $msg = [];
        $basicIds = array_keys($checkBasicIdsArr);
        $activityList = BrandActivity::bGetWikiBasicActivity($basicIds);
        foreach ($activityList as $basicId => $rows) {
            foreach ($rows as $row) {
                $channelSpuId = $checkBasicIdsArr[$basicId];
                if (in_array($row['activity_type'], BrandActivityBasic::ACTIVITY_MAP)) {
                    if (!$returnMsg) {
                        throw  new \Exception('所添加的目标商品(第三方平台商品ID：' . $channelSpuId . ')正在参加活动，暂时不支持修改，请联系运营人员进行调整！');
                    }
                    $msg[] = '所添加的目标商品(第三方平台商品ID：' . $channelSpuId . ')正在参加活动，暂时不支持修改，请联系运营人员进行调整！';
                } else if ($row['activity_type'] == BrandActivityBasic::ACTIVITY_TYPE_WIKI_RANKING) {
                    if (!$returnMsg) {
                        throw new \Exception('所添加的目标商品(第三方平台商品ID：' . $channelSpuId . ')正在上榜，暂时不支持修改，请联系运营人员进行调整！');
                    }
                    $msg[] = '所添加的目标商品(第三方平台商品ID：' . $channelSpuId . ')正在上榜，暂时不支持修改，请联系运营人员进行调整！';
                }
            }
        }
        return $msg;
    }

    /**
     * @param $basicIds
     * @param $brandId
     * @param int $storeId
     */
    public static function afterChangeBasic($basicIds, $brandId, int $storeId = 0)
    {
        self::afterEditWiki($basicIds, $brandId, $storeId);
        self::changeBrandBasicCount($brandId, $storeId);
    }


    /**
     * @param $basicIds
     * @param $brandId
     * @param int $storeId
     */
    public static function afterEditWiki($basicIds, $brandId, int $storeId = 0)
    {
        $brandId = empty($brandId) ? 0 : $brandId;
        self::_async($basicIds, $brandId, $storeId);
    }


    /**
     * @param $brandId
     * @param int $storeId
     */
    public static function changeBrandBasicCount($brandId, int $storeId = 0)
    {
        if ((!empty($brandId) && $brandId > 0) || ($storeId > 0)) {
            self::_async($brandId, $storeId);
        }
    }


    public static function bCheckCurrentBasic($basicId)
    {
        $activityList = BrandActivity::bGetWikiBasicActivity([$basicId]);
        foreach ($activityList as $rows) {
            foreach ($rows as $row) {
                if (in_array($row['activity_type'], BrandActivityBasic::ACTIVITY_MAP)) {
                    throw  new \Exception('当前商品正在参加活动，暂时不支持修改，请联系运营人员进行调整！');
                } else if ($row['activity_type'] == BrandActivityBasic::ACTIVITY_TYPE_WIKI_RANKING) {
                    throw new \Exception('当前商品正在上榜，暂时不支持修改，请联系运营人员进行调整！');
                }
            }
        }
    }

    /**
     * 品牌认领商品
     * @param $brandId int 品牌id
     * @param $wikiId int wiki表id
     * @param $basicId int wiki basic Id
     * @param $flag bool 认领和取消,true 认领 false 取消
     * @return bool
     */
    public static function setBrandWikiBasic($brandId, $wikiId, $basicId, $flag = true)
    {
        $info = mWiki::getByWhere(['id' => $wikiId]);
        if ($info['brand_id'] && $info['brand_id'] != $brandId) {
            Log::wiki_setBrandWikiBasic_debug($brandId . '认领商品失败,商品：' . $wikiId . '已经被其他品牌' . $info['brand_id'] . '认领');

            return false;
        }
        Log::wiki_setBrandWikiBasic_info($brandId . ($flag ? "认领" : "取消") . '商品：' . $wikiId . '到wiki：' . $basicId);
        if ($flag) {
            $result = mWiki::updateData(['basic_id' => $basicId, 'brand_id' => $brandId], ['id' => $wikiId]);
        } else {
            $brandId = 0;
            $result = mWiki::updateData(['basic_id' => $info['source_basic_id'], 'brand_id' => $brandId],
                ['id' => $wikiId]);
        }

        self::afterChangeBasic([$basicId], $brandId);

        return $result;
    }

    public static function online($id, $brandId, int $storeId = 0)
    {
        mWikiBasic::updateData(['basic_state' => mWikiBasic::STATE_ONLINE], ['id' => $id]);
        self::changeBrandBasicCount($brandId, $storeId);
    }

    /*
     * 更新品牌下商品数量
     * @param $brandId
     */
    public static function offline($id, $brandId, int $storeId = 0)
    {
        mWikiBasic::updateData(['basic_state' => mWikiBasic::STATE_OFFLINE], ['id' => $id]);
        self::changeBrandBasicCount($brandId, $storeId);
        if ($brandId > 0) {
            mCustomCategoryWiki::updateData(['custom_state' => mCustomCategoryWiki::STATE_DEL],
                ['basic_id' => $id, 'brand_id' => $brandId]);
        }
    }

    /**
     * @param $basicIds
     * @param $brandId
     * @param int $storeId
     */
    public static function _async_afterEditWiki($basicIds, $brandId, int $storeId = 0)
    {
        Log::wiki_afterEditWiki_info('after edit wiki', [['basicIds' => $basicIds], ['brandId' => $brandId], ['storeId' => $storeId]]);
        //注意，业务使用方，保证basicIds所对应到brandId 和 当前brandId 是一个。
        $where = ['basic_id' => $basicIds, 'status[!]' => mWiki::STATUS_DEL];
        if ($brandId > 0) {
            $where['brand_id'] = $brandId;
        }
        if ($storeId > 0) {
            $where['store_id'] = $storeId;
        }
        $list = mWiki::selectByWhere($where);
        $basicSpuList = [];
        foreach ($list as $row) {
            $basicSpuList[$row['basic_id']][] = $row;
        }
        $basicList = mWikiBasic::selectByWhere(['id' => $basicIds]);
        $basicList = array_column($basicList, null, 'id');
        foreach ($basicSpuList as $basicId => $spuList) {
            $defaultId = 0;
            foreach ($spuList as $row) {
                if ($row['is_default'] && $row['is_official']) {
                    $defaultId = $row['id'];
                }
            }
            if (!$defaultId) {
                $defaultId = $spuList[0]['id'];
            }
            $data = [];
            $basicInfo = isset($basicList[$basicId]) ? $basicList[$basicId] : [];
            if ($basicInfo) {
                $data['category_id'] = $basicInfo['category_id'];
                $data['second_category_id'] = $basicInfo['second_category_id'];
                $data['third_category_id'] = $basicInfo['third_category_id'];
                $data['four_category_id'] = $basicInfo['four_category_id'];
                $data['last_category_id'] = $basicInfo['last_category_id'];
            }
            $defaultData = $data;
            $otherData = $data;
            $defaultData['is_default'] = 1;
            $otherData['is_default'] = 0;
            if ($defaultId) {
                mWiki::updateData($defaultData, ['id' => $defaultId, 'basic_id' => $basicId]);//设为默认
                mWiki::updateData($otherData, ['id[!]' => $defaultId, 'basic_id' => $basicId]);//其他设为非默认
            }
        }
        if ($brandId) {
            mWiki::updateData(['brand_id' => $brandId], ['basic_id' => $basicIds, 'brand_id' => 0, 'store_id' => 0]);
        }
        if ($storeId > 0) {
            mWiki::updateData(['store_id' => $storeId], ['basic_id' => $basicIds, 'brand_id' => 0, 'store_id' => 0]);
        }
        self::_async_changBrandAllCustomCategory($brandId, $basicIds, $storeId);

    }

    /**
     * @param $brandId
     * @param $basicIds
     * @param int $storeId
     */
    public static function _async_changBrandAllCustomCategory($brandId, $basicIds, int $storeId = 0)
    {
        Log::wiki_changBrandAllCustomCategory_info('change brand all custom category', [$brandId, $basicIds, $storeId]);
        if ($brandId > 0) {//品牌
            $allBasicIds = mCustomCategoryWiki::selectByWhere(['brand_id' => $brandId], 'basic_id');
            $delBasicIds = $allBasicIds ? mWikiBasic::selectByWhere(['id' => $allBasicIds, 'brand_id[!]' => $brandId, 'store_id' => 0], 'id') : [];
            //已经不是品牌的wiki，自定义分类里的商品需要删除
            if ($delBasicIds) {
                mCustomCategoryWiki::updateData(['custom_state' => mCustomCategoryWiki::STATE_DEL],
                    ['basic_id' => $delBasicIds, 'brand_id' => $brandId]);
                Log::debug('不是品牌的wiki，自定义分类wiki删除,sql:' . json_encode(mCustomCategoryWiki::log()));
            }
            //非上线wiki，不在分类中
            $selectBasicIds = mWiki::selectByWhere(['brand_id' => $brandId, 'store_id' => 0, 'is_official' => 1], 'basic_id');
            $selectBasicIds = array_unique($selectBasicIds);
            $delBasicIds = $selectBasicIds ? mWikiBasic::selectByWhere(['basic_state[!]' => mWikiBasic::STATE_ONLINE, 'brand_id' => $brandId, 'store_id' => 0, 'id' => $selectBasicIds],
                'id') : [];
            Log::wiki_changBrandAllCustomCategory_info('del basicIds', $delBasicIds);
            if ($delBasicIds) {
                mCustomCategoryWiki::updateData(['custom_state' => mCustomCategoryWiki::STATE_DEL],
                    ['basic_id' => $delBasicIds, 'brand_id' => $brandId, 'custom_state[!]' => mCustomCategoryWiki::STATE_DEL]);
            }
        }
        if ($storeId > 0) {//门店
            foreach ($basicIds as $basicId) {
                StoreCustomCategoryWiki::addData(0, $storeId, $basicId);
            }
            $allBasicIds = StoreCustomCategoryWiki::selectByWhere(['store_id' => $storeId], 'basic_id');
            $delBasicIds = mWikiBasic::selectByWhere(['id' => $allBasicIds, 'store_id[!]' => $storeId, 'brand_id' => 0], 'id');
            //已经不是门店的wiki，自定义分类里的商品需要删除
            if ($delBasicIds) {
                StoreCustomCategoryWiki::updateData(['custom_state' => StoreCustomCategoryWiki::STATE_DEL],
                    ['basic_id' => $delBasicIds, 'store_id' => $storeId]);
                Log::debug('不是门店的wiki，自定义分类wiki删除,sql:' . json_encode(StoreCustomCategoryWiki::log()));
            }
            //非上线wiki，不在分类中
            $delBasicIds = mWikiBasic::selectByWhere(['basic_state[!]' => mWikiBasic::STATE_ONLINE, 'store_id' => $storeId, 'brand_id' => 0],
                'id');
            if ($delBasicIds) {
                StoreCustomCategoryWiki::updateData(['custom_state' => StoreCustomCategoryWiki::STATE_DEL],
                    ['basic_id' => $delBasicIds, 'store_id' => $storeId, 'custom_state[!]' => StoreCustomCategoryWiki::STATE_DEL]);
            }
        }

    }

    /**
     * @param $brandId
     * @param int $storeId
     * @throws \Exception
     */
    public static function _async_changeBrandBasicCount($brandId, int $storeId = 0)
    {
        Log::wiki_changeBrandBasicCount_info('change brand basic count', ['brandId' => $brandId, 'storeId' => $storeId]);
        if ($brandId > 0) {
            $brandInfo = Brand::getBrandInfoById($brandId);
            if ($brandInfo && $brandInfo['uid']) {
                $basicIds = mWiki::selectByWhere([
                    'brand_id' => $brandId,
                    'store_id' => 0,
                    'status[!]' => mWiki::STATUS_DEL,
                    'is_official' => 1,
                ], 'basic_id');
                $count = mWikiBasic::selectCountWhere([
                    'brand_id' => $brandId,
                    'store_id' => 0,
                    'basic_state' => mWikiBasic::STATE_ONLINE,
                    'id' => $basicIds,
                ]);
                UserCounter::setCounter($brandInfo['uid'], [UserCounter::TYPE_GOODS => $count]);
            } else {
                Log::debug('不存在的品牌用户信息#' . json_encode($brandInfo, JSON_UNESCAPED_UNICODE));
            }
        }

        if ($storeId > 0) {
            $storeInfo = StoreBasic::getStoreInfoById($storeId);
            if ($storeInfo && $storeInfo['uid']) {
                $basicIds = mWiki::selectByWhere([
                    'store_id' => $storeId,
                    'brand_id' => 0,
                    'status[!]' => mWiki::STATUS_DEL,
                    'is_official' => 1,
                ], 'basic_id');
                $count = mWikiBasic::selectCountWhere([
                    'store_id' => $storeId,
                    'brand_id' => 0,
                    'basic_state' => mWikiBasic::STATE_ONLINE,
                    'id' => $basicIds,
                ]);
                UserCounter::setCounter($storeInfo['uid'], [UserCounter::TYPE_GOODS => $count]);
            } else {
                Log::debug('不存在的门店用户信息#' . json_encode($storeInfo, JSON_UNESCAPED_UNICODE));
            }
        }

    }

    /**
     * 根据wiki 商品id查询 wiki 信息
     * @param $wikiSpuId wiki 商品id
     * @return array|int|mixed
     */
    public static function getWikiBasicInfoByWikiSpuId($wikiSpuId)
    {
        $wikiSpuInfos = Wiki::getWikiBaseInfos([$wikiSpuId]);
        $wikiSpuInfo = isset($wikiSpuInfos[$wikiSpuId]) ? $wikiSpuInfos[$wikiSpuId] : [];
        $basicId = ($wikiSpuInfo && $wikiSpuInfo['basic_id']) ? $wikiSpuInfo['basic_id'] : 0;
        $wikiBasicInfo = [];
        if ($basicId) {
            $wikiBasicInfos = self::getWikiBasicInfos([$basicId]);
            $wikiBasicInfo = ($wikiBasicInfos && isset($wikiBasicInfos[$basicId])) ? $wikiBasicInfos[$basicId] : 0;
        }

        return compact('wikiSpuInfo', 'wikiBasicInfo');
    }

    /**
     * 获取wiki basic的基础信息
     * @param $basicIds
     * @return array
     */
    public static function getWikiBasicInfos($basicIds)
    {
        return clsWikiBasic::getWikiBasicInfos($basicIds);

    }

    public static function getWikiBasicInfoByIds($basicIds)
    {
        $wikiBasicList = $basicIds ? self::getWikiBasicInfos($basicIds) : [];
        $spuList = $basicIds ? mWiki::selectByWhere(['basic_id' => $basicIds, 'is_default' => 1, 'status[!]' => mWiki::STATUS_DEL]) : [];
        if ($spuList) {
            foreach ($spuList as $row) {
                if (!isset($wikiBasicList[$row['basic_id']]['cover_img_url']) || empty($wikiBasicList[$row['basic_id']]['cover_img_url'])) {
                    $wikiBasicList[$row['basic_id']]['cover_img'] = $row['cover_img'];
                } else {
                    $wikiBasicList[$row['basic_id']]['cover_img'] = $wikiBasicList[$row['basic_id']]['cover_img_url'];
                }
                $wikiBasicList[$row['basic_id']]['spu_id'] = $row['id'];
            }
        }
        return $wikiBasicList;
    }


    /**
     * 获取 wiki_basic列表
     * @param array $where
     * @param array $limit
     * @return array
     */
    public static function getWikiList($where = []): array
    {
        $se_where = [];
        if ($where['brand_id']) {
            $se_where = ['brand_id' => $where['brand_id']];
        }
        $se_where['imgs_status'] = empty($where['imgs_status']) ? 2 : $where['imgs_status'];
        if ($where['id']) {
            $se_where['wiki_basic.id'] = $where['id'];
        }
        if ($where['brand_name']) {
            $se_where['brand_name'] = $where['brand_name'];
        }
        if (isset($where['wiki_basic_type']) && !empty($where['wiki_basic_type'])) {
            if ($where['wiki_basic_type'] == mWikiBasic::WIKI_BASIC_BRAND) {
                $se_where['brand_id[>]'] = 0;
            }
            if ($where['wiki_basic_type'] == mWikiBasic::WIKI_BASIC_STORE) {
                $se_where['store_id[>]'] = 0;
            }
        }
        if ($where['LIMIT']) {
            $se_where['LIMIT'] = $where['LIMIT'];
        }
        $select = ['id', 'imgs', 'brand_id', 'store_id', 'imgs_status'];
        $se_where['basic_state[!]'] = mWikiBasic::STATE_DEL;
        $wikiBasiclist = mWikiBasic::select($select, $se_where);
        $res = [];
        if ($wikiBasiclist) {
            $brandIdArr = array_column($wikiBasiclist, 'brand_id');
            $brandArr = Brand::getBrandsInfoByIds($brandIdArr);
            $storeIdArr = array_column($wikiBasiclist, 'store_id');
            $storeArr = StoreBasicService::getStoreInfoByIdArr($storeIdArr);
            foreach ($wikiBasiclist as $item) {
                $item['brand_name'] = $brandArr[$item['brand_id']]['brand_name'] ?? '';
                $item['store_name'] = $storeArr[$item['store_id']]['name'] ?? '';
                $res [] = $item;
            }
        }
        unset($se_where['LIMIT']);
        $total = mWikiBasic::count($se_where);
        $data = [
            'list' => $res ?: [],
            'total' => $total ?: 0,
        ];

        return $data;
    }

    /**
     * 根据条件更新
     * @param $where
     * @param $data
     * @return int
     */
    public static function updateData($where, $data): int
    {
        return mWikiBasic::update($data, $where)->rowCount();
    }

    /**
     * 根据basic_id 获取品牌信息
     * @param $basicId
     * @return array
     */
    public static function getBrandInfoByBasicId($basicId)
    {
        $where['id'] = $basicId;
        $brand_id = mWikiBasic::getByWhere($where, 'brand_id');
        if (!$brand_id) {
            return [];
        }
        return Brand::getBrandInfo4App($brand_id);

    }
}
